import {useState, useEffect, useCallback} from 'react'
import {AtForm, AtSwitch} from 'taro-ui'
import {View} from '@tarojs/components'
import Taro from '@tarojs/taro'

import {systemApi} from '@/api'
import DocsHeader from '@/components/doc-header'

import './index.scss'

const Index = () => {
  const [isDebugMode, setIsDebugMode] = useState(false)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    console.log('系统设置页面加载完成')
    // 可以在这里获取初始设置状态
    // initializeSettings()
  }, [])

  const debugHandler = useCallback(async (checked: boolean) => {
    if (loading) return // 防止重复调用

    setLoading(true)
    setIsDebugMode(checked)
    console.log('切换调试模式:', checked)

    try {
      const resp = await systemApi.ping()
      console.log('API响应:', resp)

      await Taro.showToast({
        title: checked ? '调试模式已开启' : '调试模式已关闭',
        icon: 'success'
      })
    } catch (error) {
      console.error('API调用失败:', error)

      // 失败时回滚状态
      setIsDebugMode(!checked)

      await Taro.showToast({
        title: '操作失败，请重试',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }, [loading])

  return (
    <View>
      <DocsHeader title='系统设置' />
      <AtForm>
        <AtSwitch
          title='HTTP调试'
          checked={isDebugMode}
          disabled={loading}
          onChange={debugHandler}
        />
      </AtForm>
    </View>
  )
}

export default Index
